package org.csu.gp_store.controller;

import org.csu.gp_store.bo.*;
import org.csu.gp_store.common.CommonResponse;
import org.csu.gp_store.entity.*;
import org.csu.gp_store.service.*;
import org.csu.gp_store.util.TokenUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/orders")
public class OrderController {


    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private CartItemService cartItemService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private ProductService productService;

    @Autowired
    private EvaluationService  evaluationService;

    //通过购物车提交订单
    @PostMapping("/additions")
    @ResponseBody
    public CommonResponse<Orders> insertOrderAndOrderItemByCart(@RequestHeader("MyToken") String MyToken,
                                                                @RequestBody AddOrderBO addOrderBO) {

        if (null ==MyToken ||"".equals(MyToken)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }
            String accountID = TokenUtil.getUserIdByToken(MyToken);
        if (null==accountID ||"".equals(accountID))
        {
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }
        try {
            Orders orders = new Orders();
            orders.setAccountID(Long.valueOf(accountID));
            orders.setBillAddress(addOrderBO.getAddress());
            orders.setBillName(addOrderBO.getName());
            orders.setBillPhone(addOrderBO.getPhone());
            orders.setBillNotes(addOrderBO.getNotes());
            orders.setTotalAmount(BigDecimal.valueOf(Double.parseDouble(addOrderBO.getAmount())));
            orders.setStatus(0);
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            orders.setAddTime(timestamp);
            orderService.insertOrder(orders);
            CartItem cartItem;
            Item item;
            Product product;
            List<String> cartIDs =addOrderBO.getCartIDs();
            System.out.println(cartIDs);
            for (String cartID : cartIDs) {
                cartItem = cartItemService.getCartItemByCartID(Long.valueOf(cartID));
                item = ItemBO.ItemBOToItem(itemService.getItemByItemID(cartItem.getItemID()));
                product = ProductBO.productBOToProduct(productService.getProductByProductID(item.getProductID()));
                orderItemService.insertOrderItem(OrderItem.toOrderItem(product, item, cartItem, orders));
                cartItemService.deleteItemFromCart(cartItem.getCartID());
            }
            return CommonResponse.createForSuccess(orders);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return CommonResponse.createForError("出现未知错误，请稍后重试");
    }

    //商城直接购买提交订单
    @PostMapping("/addition")
    @ResponseBody
    public CommonResponse<Orders> insertOrderAndOrderItemByBuyingAtOnce(@RequestHeader("MyToken") String MyToken,
                                                                        @RequestBody Map<String,String> obj) {
        if (null ==MyToken ||"".equals(MyToken)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }
        String accountID=TokenUtil.getUserIdByToken(MyToken);
        if (null==accountID||"".equals(accountID)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }
        try {
            Orders orders = new Orders();
            orders.setAccountID(Long.valueOf(accountID));
            orders.setBillAddress(obj.get("address"));
            orders.setBillName(obj.get("name"));
            orders.setBillPhone(obj.get("phone"));
            orders.setBillNotes(obj.get("notes"));
            orders.setTotalAmount(BigDecimal.valueOf(Double.parseDouble(obj.get("amount"))));
            orders.setStatus(0);
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            orders.setAddTime(timestamp);
            orderService.insertOrder(orders);
            Item item;
            Product product;
            item = ItemBO.ItemBOToItem(itemService.getItemByItemID(Long.valueOf(obj.get("itemID"))));
            product = ProductBO.productBOToProduct(productService.getProductByProductID(item.getProductID()));
            orderItemService.insertOrderItem(OrderItem.toOrderItem(product, item, orders, Integer.parseInt(obj.get("quantity"))));
            return CommonResponse.createForSuccess(orders);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonResponse.createForError("出现未知错误，请稍后重试");
    }

    @GetMapping("/orderItems/{orderID}")
    @ResponseBody
    public  CommonResponse<List<OrderItem>> getOrderItemsByOrderID(@PathVariable @NotNull String orderID,@RequestHeader("MyToken") String MyToken){
        if (null ==MyToken ||"".equals(MyToken)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }
        String accountID=TokenUtil.getUserIdByToken(MyToken);
        if (null==accountID||"".equals(accountID)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }
        return CommonResponse.createForSuccess(orderItemService.getOrderItemsByOrderID(Long.valueOf(orderID)));
    }


    @PatchMapping("/order/orderItem/update/{orderID}")
    public CommonResponse<String> updateOrderAndOrderItemStatus(@PathVariable @NotNull  String orderID,
                                                    @RequestHeader("MyToken") String MyToken,
                                                    @RequestParam("status") int status) {
        if (null ==MyToken ||"".equals(MyToken)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }
        try {
              if (orderService.updateOrderStatus(Long.valueOf(orderID),status)==1) {
                  List<OrderItem> orderItemList= orderItemService.getOrderItemsByOrderID(Long.valueOf(orderID));
                  for (OrderItem orderItem: orderItemList){
                      orderItemService.updateOrderItemStatus(orderItem.getIndexID(), status);
                  }
              }
              return CommonResponse.createForSuccessMsg("修改成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        return CommonResponse.createForError("出现未知错误，请稍后重试。");
    }

    @PatchMapping("/order/update/{orderID}")
    public CommonResponse<String> updateOrderStatus(@PathVariable @NotNull  String orderID,
                                                    @RequestHeader("MyToken") String MyToken,
                                                    @RequestParam("address")String address,
                                                    @RequestParam("name")String name,
                                                    @RequestParam("phone")String phone,
                                                    @RequestParam("notes")String notes,
                                                    @RequestParam("total_amount") String amount,
                                                    @RequestParam("status") int status) {
        if (null ==MyToken ||"".equals(MyToken)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }
        try {
            Orders orders =orderService.getOrderByOrderID(Long.valueOf(orderID));
            orders.setBillAddress(address);
            orders.setBillName(name);
            orders.setBillPhone(phone);
            orders.setBillNotes(notes);
            orders.setStatus(status);
            orders.setTotalAmount(BigDecimal.valueOf(Double.parseDouble(amount)));
            if (orderService.updateOrder(Long.valueOf(orderID), orders)==1){
                return CommonResponse.createForSuccessMsg("修改成功");
            }else {
                return CommonResponse.createForSuccessMsg("修改失败");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return CommonResponse.createForError("出现未知错误，请稍后重试。");
    }

    @PatchMapping("/orderItem/update/{orderID}")
    @ResponseBody
    public CommonResponse<String> updateOrderAndOrderItemStatus(@PathVariable @NotNull String orderID,
                                                                @RequestParam  int status,
                                                                @RequestHeader("MyToken") String MyToken){
        if (null ==MyToken ||"".equals(MyToken)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }
        try {
            if(orderItemService.updateOrderItemStatus(Long.valueOf(orderID),status)==1){

                return CommonResponse.createForSuccessMsg("修改成功");
            }else {
                return CommonResponse.createForSuccessMsg("修改失败");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return CommonResponse.createForError("出现未知错误，请稍后再试！");
    }

    @DeleteMapping("/deletion/{orderID}")
    @ResponseBody
    public CommonResponse<String> deleteOrder( @RequestHeader("MyToken") String MyToken,@PathVariable @NotNull String orderID){

        if (null ==MyToken ||"".equals(MyToken)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }

        try{
            if(orderService.deleteOrder(Long.valueOf(orderID))==1){
                List<OrderItem> orderItemList =orderItemService.getOrderItemsByOrderID(Long.valueOf(orderID));
                for (OrderItem orderItem :orderItemList){
                    orderItemService.deleteOrderItem(orderItem.getOrderID());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return CommonResponse.createForSuccessMsg("删除失败");
        }
        return  CommonResponse.createForSuccessMsg("删除成功");
    }
    //根据accountID获取订单列表
    @GetMapping("/orders/account")
    @ResponseBody
    public CommonResponse<List<OrdersBO>> getOrderSBOByAccountID(@RequestHeader("MyToken") String MyToken){

        if (null ==MyToken ||"".equals(MyToken)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }
        String accountID=TokenUtil.getUserIdByToken(MyToken);
        if (null==accountID||"".equals(accountID)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }

        List<Orders> ordersList=orderService.getOrderListByAccountID(Long.valueOf(accountID));
        List<OrdersBO> ordersBOList=new ArrayList<>();
        List<OrderItem> orderItemList;
        for (int i=ordersList.size()-1;i>=0;i--){
            Orders orders=ordersList.get(i);
            orderItemList=orderItemService.getOrderItemsByOrderID(orders.getOrderID());
            ordersBOList.add(OrdersBO.toOrdersBO(orders,orderItemList));
        }

        return CommonResponse.createForSuccess(ordersBOList);
    }
    //根据accountID和status获取订单列表
    @GetMapping("/orders")
    @ResponseBody
    public CommonResponse<List<OrdersBO>> getOrderSBOByAccountID(@RequestHeader("MyToken") String MyToken,
                                                                 @RequestParam("status")int status){

        if (null ==MyToken ||"".equals(MyToken)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }
        String accountID=TokenUtil.getUserIdByToken(MyToken);
        if (null==accountID||"".equals(accountID)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }

        List<Orders> ordersList=orderService.getOrderListByAccountIDAndStatus(Long.valueOf(accountID),status);
        List<OrdersBO> ordersBOList=new ArrayList<>();
        List<OrderItem> orderItemList;
        for (Orders orders :ordersList){
            orderItemList=orderItemService.getOrderItemsByOrderID(orders.getOrderID());
            ordersBOList.add(OrdersBO.toOrdersBO(orders,orderItemList));
        }
        return CommonResponse.createForSuccess(ordersBOList);
    }

    //根据productName搜索订单
    @GetMapping("/productName/{productName}")
    @ResponseBody
    public  CommonResponse<List<OrdersBO>> getOrdersBOLikeProductName(@RequestHeader("MyToken") String MyToken,
                                                      @PathVariable String productName){
        if (null ==MyToken ||"".equals(MyToken)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }
        String accountID=TokenUtil.getUserIdByToken(MyToken);
        if (null==accountID||"".equals(accountID)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }

            List<OrdersBO> ordersBOList=new ArrayList<>();
            List<OrderItem> orderItemList=orderItemService.getOrderItemListLikeProductName(productName);
            List<Orders> ordersList = new ArrayList<>();
            for (OrderItem orderItem :orderItemList){
                Orders orders=orderService.getOrderByOrderID(orderItem.getOrderID());
                if (!ordersList.contains(orders)) {
                    ordersList.add(orders);
                }
            }
        for (int i=ordersList.size()-1;i>=0;i--){
            Orders orders=ordersList.get(i);
            if(orders.getAccountID().compareTo(Long.valueOf(accountID))==0) {
                orderItemList = orderItemService.getOrderItemsByOrderID(orders.getOrderID());
                ordersBOList.add(OrdersBO.toOrdersBO(orders, orderItemList));
            }
        }
        return CommonResponse.createForSuccess(ordersBOList) ;
    }

    //向OrderItem中添加评价。
    @PostMapping("/evaluation/insert")
    @ResponseBody
    public CommonResponse<String> insertEvaluation(@RequestHeader("MyToken") String MyToken,
                                                   @RequestBody List<Evaluation> evaluationList){
        if (null ==MyToken ||"".equals(MyToken)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }
        String accountID=TokenUtil.getUserIdByToken(MyToken);
        if (null==accountID||"".equals(accountID)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }
        try {
            for (Evaluation evaluation :evaluationList){
                Timestamp timestamp = new Timestamp(System.currentTimeMillis());
                evaluation.setAccountID(Long.valueOf(accountID));
                evaluation.setTime(timestamp);
                if (evaluationService.insertEvaluation(evaluation)!=1){
                    return CommonResponse.createForSuccessMsg("添加失败");
                }else{
                    OrderItem orderItem=orderItemService.getOrderItemByIndexID(evaluation.getIndexID());
                    orderItemService.updateOrderItemStatus(evaluation.getIndexID(), 4);
                    orderService.updateOrderStatus(orderItem.getOrderID(), 4);
                }
            }
          return  CommonResponse.createForSuccessMsg("添加成功");
        }catch (Exception e){
                e.printStackTrace();
        }
        return CommonResponse.createForError("出现未知错误，请稍后重试！");
    }
    //修改评价。
    @PostMapping("/evaluation/update")
    @ResponseBody
    public CommonResponse<String> updateEvaluation(@RequestHeader("MyToken") String MyToken,
                                                   @RequestBody Evaluation evaluation){
        if (null ==MyToken ||"".equals(MyToken)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }
        String accountID=TokenUtil.getUserIdByToken(MyToken);
        if (null==accountID||"".equals(accountID)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }
        try {
            evaluation.setAccountID(Long.valueOf(accountID));
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            evaluation.setTime(timestamp);
            if (evaluationService.updateEvaluation(evaluation)==1){
                return CommonResponse.createForSuccessMsg("修改成功");
            }else {
                return CommonResponse.createForSuccessMsg("修改失败");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return CommonResponse.createForError("出现未知错误，请稍后重试！");
    }

    //根据用户ID获取历史评价表
    @GetMapping("/account/evaluation")
    @ResponseBody
    public CommonResponse<List<EvaluationBO>> getOrderItemAndEvaluationByAccountID(@RequestHeader("MyToken") String MyToken){
        if (null ==MyToken ||"".equals(MyToken)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }
        String accountID=TokenUtil.getUserIdByToken(MyToken);
        if (null==accountID||"".equals(accountID)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }
        try {
            List<EvaluationBO> evaluationBOList=new ArrayList<>();
            List<Evaluation> evaluationList = evaluationService.getEvaluationByAccountID(Long.valueOf(accountID));
            for (Evaluation evaluation :evaluationList){
               OrderItem orderItem=orderItemService.getOrderItemByIndexID(evaluation.getIndexID());
               Item item=ItemBO.ItemBOToItem(itemService.getItemByItemID(orderItem.getItemID()));
               Product product =ProductBO.productBOToProduct(productService.getProductByProductID(evaluation.getProductID()));
               evaluationBOList.add(EvaluationBO.toEvaluationBO(evaluation,orderItem,product,item));
            }
            return CommonResponse.createForSuccess(evaluationBOList);
        }catch (Exception e){
            e.printStackTrace();
        }

       return  CommonResponse.createForError("出现未知错误，请稍后再试！");
    }



}
